package com.dituhui.tool.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Properties;

/**
 * 配置文件读取工具
 * 
 * @author liweigu
 * 
 */
public class Constants {
	// 用于缓存
	private static HashMap<String, Properties> Props = new HashMap<String, Properties>();
	// 默认配置文件
	private static String DefaultConfig = "config.properties";

	/**
	 * 从"config.properties"读取配置值
	 * 
	 * @param key 配置key
	 * @return 配置值
	 */
	public static String getValue(String key) {
		return getValue(key, DefaultConfig);
	}

	/**
	 * 读取配置值
	 * 
	 * @param key 配置key
	 * @param file 配置文件，如"config.properties"
	 * @return 配置值
	 */
	public static String getValue(String key, String file) {
		Properties prop;
		String value = null;
		try {
			if (Props.containsKey(file)) {
				prop = Props.get(file);
			} else {
				prop = readPropertiesFile(file, Constants.class);
			}
			value = prop.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	private static Properties readPropertiesFile(String fileName, Class clazz) {
		InputStream inStream = readFromUsrDir(fileName);

		if (inStream == null) {
			inStream = readFromClassPath(fileName, clazz);
		}
		Properties prop = new Properties();
		try {
			if (inStream != null) {
				prop.load(inStream);
				inStream.close();
			} else {
				prop = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			prop = null;
		}
		return prop;
	}

	private static InputStream readFromUsrDir(String fileName) {
		String filePath = System.getProperty("user.dir") + File.separator + fileName;
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(filePath);
		} catch (FileNotFoundException localFileNotFoundException) {
		}
		return inStream;
	}

	private static InputStream readFromClassPath(String fileName, Class clazz) {
		return clazz.getClassLoader().getResourceAsStream(fileName);
	}
}
